package gameserver;
import game.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import sun.misc.IOUtils;

import com.sun.net.httpserver.*;

public class GameHandler implements HttpHandler {

	Game game;
	
	public GameHandler(Game game ) {
		this.game = game;
	}
	
	public static String convertStreamToString(java.io.InputStream is) {
	    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
	    return s.hasNext() ? s.next() : "";
	}
	
	@Override
	public void handle(HttpExchange exchange) throws IOException {
		// TODO Auto-generated method stub
		
		InputStream input = exchange.getRequestBody();
		
		String response = this.game.createClient(this.convertStreamToString(input)).work();
				
		OutputStream output = exchange.getResponseBody();
		
		exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length());
        exchange.getResponseBody().write(response.getBytes());
        exchange.close();
	}

}
